'''
Module: ep_main.py
Purpose: Implements the UI for the Earley parser exercise.
Author: Avishay Alon
'''
#########################################
### Imports
#########################################
import sys
import os
from ep_core import EarleyParser
from ep_grammar import Grammar

#########################################
### Globals
#########################################
USAGE = '%s <grammar filepath> <input filepath>' % (__file__, )
LINE_COMMENT_OUT_MAGIC = '#'

#########################################
### Functions
#########################################
def main(args):
    ''' Main function:
        1. Validates inpurt
        2. Creates a grammar and an Earley parser
        3. Parses the input according to the grammar and outputs the result. '''
    grammar_filepath, input_filepath = args
    incorrect_paths = [ path for path in args if not os.path.isfile(path) ]
    if incorrect_paths:
        raise ValueError('Incorrect file paths %s' % incorrect_paths)

    with open(input_filepath, 'rb') as input_file:
        input_lines = [ line.strip() for line in input_file.readlines() if line.strip() and
            not line.startswith(LINE_COMMENT_OUT_MAGIC) ]

    try:
        grammar = Grammar(grammar_filepath)
    except ValueError as e:
        print e
        raise
    # print grammar
    earley_parser = EarleyParser(grammar)

    for line in input_lines:
        result = earley_parser.parse(line.split())
        print line
        print int(result)
        if result:
            roots = earley_parser.create_parse_trees()
            print 'Total: %d trees' % (len(roots), )
            for root in roots:
                root.list_print()
        print '-----------------------------------------'
        
        # if not result:
            # break
    return result

if __name__ == '__main__':
    if len(sys.argv) == 3:
        main(sys.argv[1:])
    else:
        print USAGE
